package ws

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"time"
)

type Message map[string]interface{}

func (m *Message) String() string {
	b, _ := json.Marshal(m)
	return string(b)
}

type Client struct {
	Name string
	Conn *websocket.Conn
	Attr map[string]interface{}
}

func NewClient(name string, conn *websocket.Conn) *Client {
	return &Client{Conn: conn, Attr: map[string]interface{}{}, Name: name}
}
func (c *Client) SetAttr(name string, value interface{}) {
	c.Attr[name] = value
}

func (c *Client) GetAttr(name string) interface{} {
	return c.Attr[name]
}
func (c *Client) Start(manager WSClientManager) {
	_ = clientManager.RegisteClient(c.Name, c)

	for {
		var m map[string]interface{}
		err := c.Conn.ReadJSON(&m)
		if err != nil {
			fmt.Println("读取数据异常", err)
			if _, ok := err.(*websocket.CloseError); ok {
				fmt.Println("连接断开", c.Name)
				manager.UnRegisteClient(c.Name, c)
				break
			}
			continue
		}
		// 跳过心跳检测数据包
		if m["cmdType"].(float64) == 101 {
			continue
		}

		cmdT := m["cmdType"].(float64)

		if cmdT == MSG_CMD_CHAT {
			m1 := Message{
				"cmdType":  1,
				"showType": 1,
				"msg":      m["msg"].(string),
				"type":     1,
				"sender":   c.Name,
				"sendTime": time.Now().Format("2006-01-02 15:04:05"),
			}
			m2 := Message{
				"cmdType":  2,
				"showType": 1,
				"msg":      m["msg"].(string),
				"type":     1,
				"sender":   c.Name,
				"sendTime": time.Now().Format("2006-01-02 15:04:05"),
			}
			_ = manager.BroadcastMsg(c.Name, m1.String(), true)
			_ = manager.BroadcastMsg(c.Name, m2.String(), false)
		}

	}

}
func (c *Client) Write(msg string) error {
	return c.Conn.WriteMessage(websocket.TextMessage, []byte(msg))
}
